<?php

namespace app\api\controller\kuyou\applet;

use app\common\exception\UploadException;
use app\common\library\Upload;
use app\api\model\kuyou\applet\Area;
use app\api\model\kuyou\applet\Sets;
use app\common\model\Version;
use fast\Random;
use think\Config;
use think\Db;
use think\Cache;
use think\Hook;
use fast\Tree;
use think\Exception;
class Commons extends Common
{
    protected $noNeedLogin = ['init','getmenu'];
    protected $noNeedRight = '*';

    public function init()
    {
        if ($version = $this->request->request('version')) {
            $lng = $this->request->request('lng');
            $lat = $this->request->request('lat');

            $upload = Config::get('upload');
            if ($upload['storage'] != 'local' && isset($upload['uploadmode']) && $upload['uploadmode'] != 'server') {
                set_addon_config($upload['storage'], ["uploadmode" => "server"], false);

                $upload = \app\common\model\Config::upload();
                Hook::listen("upload_config_init", $upload);

                $upload = Config::set('upload', array_merge(Config::get('upload'), $upload));
            }

            $upload['cdnurl'] = $upload['cdnurl'] ? $upload['cdnurl'] : cdnurl('', true);
            $upload['uploadurl'] = preg_match("/^((?:[a-z]+:)?\/\/)(.*)/i", $upload['uploadurl']) ? $upload['uploadurl'] : url($upload['storage'] == 'local' ? '/api/common/upload' : $upload['uploadurl'], '', false, true);

            $content = [
                'citydata'    => Area::getCityFromLngLat($lng, $lat),
                'versiondata' => Version::check($version),
                'uploaddata'  => $upload,
                'coverdata'   => Config::get("cover"),
            ];
            $this->success('', $content);
        } else {
            $this->error(__('Invalid parameters'));
        }
    }

    public function upload()
    {
        Config::set('default_return_type', 'json');
        Config::set('upload.cdnurl', '');
        $chunkid = $this->request->post("chunkid");
        if ($chunkid) {
            if (!Config::get('upload.chunking')) {
                $this->error(__('Chunk file disabled'));
            }
            $action = $this->request->post("action");
            $chunkindex = $this->request->post("chunkindex/d");
            $chunkcount = $this->request->post("chunkcount/d");
            $filename = $this->request->post("filename");
            $method = $this->request->method(true);
            if ($action == 'merge') {
                $attachment = null;
                try {
                    $upload = new Upload();
                    $attachment = $upload->merge($chunkid, $chunkcount, $filename);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
            } elseif ($method == 'clean') {
                try {
                    $upload = new Upload();
                    $upload->clean($chunkid);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            } else {
                $file = $this->request->file('file');
                try {
                    $upload = new Upload($file);
                    $upload->chunk($chunkid, $chunkindex, $chunkcount);
                } catch (UploadException $e) {
                    $this->error($e->getMessage());
                }
                $this->success();
            }
        } else {
            $attachment = null;
            $file = $this->request->file('file');
            try {
                $upload = new Upload($file);
                $attachment = $upload->upload();
            } catch (UploadException $e) {
                $this->error($e->getMessage());
            }

            $this->success(__('Uploaded successful'), ['url' => $attachment->url, 'fullurl' => cdnurl($attachment->url, true)]);
        }

    }

    public function getcode(){
        if ($this->request->isPost()) {
            $type = $this->request->post('type');
            $code = $this->request->post('code');
            if(empty($type)){
                $this->error('请输入编号类型','',500);
            }
            $code = $this->getCodes($code,$type);
            if($code){
                $this->success('查询成功',$code,200);
            }else{
                $this->error('查询失败','',500);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    public function getmenu(){
        if ($this->request->isPost()) {
            
            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $admin = \think\Cache::get($token);
            $adminId = isset($admin['id'])?$admin['id']:0;
            $group_id = Db::name('auth_group_access')->where(['uid'=>$adminId])->value('group_id');
            $auth_id = Db::name('auth_group')->where(['id'=>$group_id])->value('rules');
            $auth_id = explode(',',$auth_id);
            
            $list = Db::name('auth_rule')->where(['status'=>'normal','name'=>['like','kuyou%']])->order(['weigh'=>'DESC'])->field('id,pid,name,title,ismenu,weigh,status,icon')->select();

            foreach ($list as $list_k=>$list_v){
                if(in_array($list_v['id'],$auth_id) || $group_id==1){
                    $list[$list_k]['is_checked'] = 1;
                }else{
                    $list[$list_k]['is_checked'] = 2;
                }
            }

            $tree = Tree::instance();
            $tree->init($list, 'pid');
            $list = $tree->getTreeArray(0);

            $type = $this->request->post('type');
            $type = $type==2?2:1;
            if($type==2){
                $arr = ['kuyou/buy/default','kuyou/sales','kuyou/retail','kuyou/stores/default','kuyou/capital','kuyou/order/default'];
                foreach ($list as $list_k=>$list_v){
                    foreach ($list_v['childlist'] as $list_k2=>$list_v2){
                        if(in_array($list_v2['name'],$arr)){
                            unset($list_v['childlist'][$list_k2]);
                        }
                    }
                    sort($list_v['childlist']);
                    $list[$list_k]['childlist'] = $list_v['childlist'];
                }
            }

            if($list){
                $this->success('查询成功',$list,200);
            }else{
                $this->error('查询失败','',500);
            }
        }else{
            $this->error('请求方式错误','',250);
        }
    }

    public function index(){
        if ($this->request->isPost()) {
            $data = $_POST;
            if(isset($data['type']) && $data['type']=='initialization'){
                $limitTable   = [
                    'kuyou_accounts','kuyou_accounts_copewith','kuyou_accounts_log','kuyou_accounts_receivable','kuyou_accounts_transfer',
                    'kuyou_accounts_transfer_info','kuyou_address','kuyou_adjustment','kuyou_adjustment_info','kuyou_allocation',
                    'kuyou_allocation_info','kuyou_assemble','kuyou_assemble_info','kuyou_assemble_info_temp','kuyou_assemble_temp',
                    'kuyou_attr_combination','kuyou_attribute','kuyou_aux_combination','kuyou_auxiliary','kuyou_collection','kuyou_collection_account',
                    'kuyou_collection_sale','kuyou_cost','kuyou_customer_goodscoding','kuyou_customers','kuyou_customers_user',
                    'kuyou_customertype','kuyou_expend_type','kuyou_expenditure','kuyou_expenditure_info','kuyou_goods','kuyou_goods_attr',

                    'kuyou_goods_batch','kuyou_goods_batch_exchange_info','kuyou_goods_batch_info','kuyou_goods_batch_log','kuyou_goods_batch_sale_info',
                    'kuyou_goods_batch_salee_info','kuyou_goods_batch_stock','kuyou_goods_exchange','kuyou_goods_exchange_info','kuyou_goods_excpur',
                    'kuyou_goods_excpur_info','kuyou_goods_log','kuyou_goods_period','kuyou_goods_price','kuyou_goods_purchase','kuyou_goods_purchase_info',
                    'kuyou_goods_purchase_order','kuyou_goods_purchase_order_info','kuyou_goods_purchase_summary','kuyou_goods_purord','kuyou_goods_purord_info',
                    'kuyou_goods_saleexc','kuyou_goods_saleexc_info','kuyou_goods_saleord','kuyou_goods_saleord_info','kuyou_goods_sales','kuyou_goods_sales_exchange',
                    'kuyou_goods_sales_exchange_info','kuyou_goods_sales_info','kuyou_goods_sales_order','kuyou_goods_sales_order_info','kuyou_goods_sales_profit',
                    'kuyou_goods_sales_summary','kuyou_goods_serial','kuyou_goods_serial_log','kuyou_goods_stock','kuyou_goods_stock_warning','kuyou_goods_store_info',

                    'kuyou_goods_type','kuyou_income','kuyou_income_info','kuyou_income_type','kuyou_inventory','kuyou_inventory_info','kuyou_inventory_serial',
                    'kuyou_inventory_serial_info','kuyou_invoicing','kuyou_invoicing_log','kuyou_payment','kuyou_payment_account','kuyou_payment_log',
                    'kuyou_payment_sale','kuyou_sales_invoicing','kuyou_sales_invoicing_log','kuyou_sales_payment_log','kuyou_settlementtype','kuyou_spendingtype',
                    'kuyou_split','kuyou_split_info','kuyou_split_info_temp','kuyou_split_temp','kuyou_staff_member','kuyou_stores','kuyou_suppliers','kuyou_suppliers_user',
                    'kuyou_supplyertype','kuyou_transfers','kuyou_unit','kuyou_unit_conversion','kuyou_warehouse','kuyou_warehouse_info','kuyou_warehousing',
                    'kuyou_warehousing_info','kuyou_writeoff','kuyou_writeoff_info','kuyou_writeoff_log',
                ];
                $result = false;
                Db::startTrans();
                try {
                    foreach ($limitTable as $limitTable_k=>$limitTable_v){
                        $result = Db::name($limitTable_v)->where(['id'=>['>',0]])->delete();
                    }
                    Db::commit();
                } catch (Exception $e) {
                    Db::rollback();
                    $this->error($e->getMessage());
                }
                if(isset($result) && $result !== false){
                    $this->success('初始化成功');
                }else{
                    $this->error('初始化失败');
                }
            }
            $this->error(__('Parameter %s can not be empty', ''));
        }
    }
    
    /**
     * 获取常用
     * @ApiMethod (POST)
     */
    public function getCommonly(){
        if ($this->request->isPost()) {
            $type = $this->request->post('type');
            $list_type = $this->request->post('list_type');
            $list_type = !empty($list_type)?$list_type:1;
            $list_type = $list_type==1?1:2;

            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $user = \think\Cache::get($token);
            if(empty($user)){
                $this->error('请先登陆','',401);
            }
            switch ($type){
                case 1:
                    $field = 'rules';$table = 'user_rule';
                    break;
                case 2:
                    $field = 'applet';$table = 'user_applet_rule';
                    break;
                default:
            }
            if(!isset($field)){
                $this->error('权限类型错误','',500);
            }
            $group_ids = Db::name('kuyou_user_applet')->where(['user_id'=>$user['id']])->value($field);
            $group_ids = explode(',',$group_ids);

            $list = Db::name('auth_rule')
                ->where(['status'=>'normal','id'=>['in',$group_ids]])
                ->field('id,pid,name,title,ismenu,weigh,status')
                ->select();

            if($list_type==2){
                $tree = Tree::instance();
                $tree->init($list, 'pid');
                $list = $tree->getTreeArray(0);
            }

            if($list){
                $this->success('查询成功',$list,200);
            }else{
                $this->success('未查询到相关数据','',200);
            }

        }else{
            $this->error('请求方式错误','',250);
        }
    }
    
    /**
     * 设置常用
     * @ApiMethod (POST)
     */
    public function setCommonly(){
        if ($this->request->isPost()) {
            $ids = $this->request->post('ids');
            if(is_array($ids)){
                $ids = implode(',',$ids);
            }
            $type = $this->request->post('type');

            $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
            $user = \think\Cache::get($token);
            if(empty($user)){
                $this->error('请先登陆','',401);
            }
            switch ($type){
                case 1:
                    $field = 'rules';
                    break;
                case 2:
                    $field = 'applet';
                    break;
                default:
            }
            if(!isset($field)){
                $this->error('权限类型错误','',500);
            }
            $group_ids = Db::name('kuyou_user_applet')->where(['user_id'=>$user['id']])->value('id');
            if($group_ids){
                $res = Db::name('kuyou_user_applet')->where(['user_id'=>$user['id']])->update([$field=>$ids]);
            }else{
                $res = Db::name('kuyou_user_applet')->insert([$field=>$ids,'user_id'=>$user['id'],'createtime'=>time(),'updatetime'=>time()]);
            }

            if($res){
                $this->success('设置成功','',200);
            }else{
                $this->error('设置失败','',500);
            }

        }else{
            $this->error('请求方式错误','',250);
        }
    }
    
    public function index_info(){
        $info = Cache::get('indexInfo');
        if(empty($info)){
            $this->setindexInfo();
            $info = Cache::get('indexInfo');
        }
        $this->success('查询成功',$info,200);
    }
    function adminList(){
        $list = Db::name('admin')->column('username','id');
        return $list;
    }
    function setindexInfo(){
        //获取设置
        $set= \think\Db::name('kuyou_sets')->field('type,name,value,is_checked,set')->select();
        $setList = [];
        foreach ($set as $set_k=>$set_v){
            if(!empty($set_v['set'])){
                $set_v['set'] = unserialize($set_v['set']);
            }
            $setList[$set_v['name']] = $set_v;
        }
        //数量价格格式化
        $price_decimal  = $setList['price_decimal']['value'];
        $number_decimal  = $setList['number_decimal']['value'];
        $stmen = Db::name('kuyou_staff_member')->column('name','id');


        $info = [];
        $start = strtotime(date('Y-m-d'));
        $end = strtotime(date('Y-m-d'). ' 23:59:59');
        $where = [];
        $where['purchase_time'] = ['BETWEEN',[$start,$end]];
        $pay = Db::name('kuyou_goods_purchase')->where($where)->sum('pay_money');//今日付款
        $sale = Db::name('kuyou_goods_sales')->where($where)->sum('pay_money');//今日收款
        $info['pay'] = round($pay,$price_decimal);
        $info['sale'] = round($sale,$price_decimal);

        $result = ['sale_money'=>'','sales_discount'=>'','collection_all'=>'',
            'cost_all'=>'','discount_all'=>'','payment_all'=>'',
            'surplus_loss'=>'','main_business'=>'','other_income'=>'','profit'=>''];
        foreach ($result as $result_k=>$result_v){
            $result[$result_k] = round($result_v,$price_decimal);
        }
        $goods = Db::name('kuyou_goods')->select();
        foreach ($goods as $goods_k=>$goods_v){
            $res = (new \app\admin\controller\kuyou\Goods())->getProfit($goods_v['goods_code'],$start,$end);
            foreach ($result as $result_k=>$result_v){
                $result[$result_k] += isset($res[$result_k])?(float)$res[$result_k]:0;
            }
        }
        foreach ($result as $result_k=>$result_v){
            $result[$result_k] = round($result_v,$price_decimal);
        }

        $profit = isset($result['profit'])?$result['profit']:$result['profit'];//利润
        $info['profit'] = round($profit,$price_decimal);

        $map = [];
        $map['sp.purchase_time'] = ['BETWEEN',[$start,$end]];
        $sup = Db::name('kuyou_customers')->alias('sp')
            ->join('kuyou_customertype gt','sp.customertype_id=gt.id')
//            ->where($map)
            ->field('sp.id,sp.opening_prepayment,sp.customer_code,sp.customer_name,sp.receive_account,gt.type_name')
            ->order('sp.customer_code asc')
            ->select();

        $field = empty(input('field'))?'createtime':trim(input('field'));
        $order = empty(input('sort'))?'ASC':trim(input('sort'));


        $all_balance = 0;
        foreach ($sup as $sup_k=>$sup_v){
            $balance = round($sup_v['receive_account']-$sup_v['opening_prepayment'],$price_decimal);
            $list = Db::name('kuyou_accounts_receivable')
                ->where($where)
                ->where(['customers_id'=>$sup_v['id']])
                ->order([$field=>$order])
                ->select();
            foreach ($list as $list_k=>$list_v){
                $balance    += $list_v['receivable'];
                $balance    -= $list_v['advance'];
            }
            $all_balance    += $balance;
        }

        $info['receivable_unit'] = '元';
        $all_balance = round($all_balance,$price_decimal);
        if($all_balance>10000 || $all_balance<-10000){
            $all_balance = round($all_balance/10000,$price_decimal);
            $info['receivable_unit'] = 'W';
        }else if(($all_balance>1000 && $all_balance<=10000) || ($all_balance<-1000 && $all_balance>=-10000)){
            $all_balance = round($all_balance/1000,$price_decimal);
            $info['receivable_unit'] = 'K';
        }
        $info['receivable'] = $all_balance;

        $sup = Db::name('kuyou_suppliers')->alias('sp')
            ->join('kuyou_supplyertype gt','sp.supplyertype_id=gt.id')
            //->where($map)
            ->order('sp.supplyer_code asc')
            ->field('sp.id,sp.receive_account,sp.supplyer_code,sp.supplyer_name,sp.opening_payable,sp.opening_prepayment,gt.supplier_type_name')
            ->select();

        $field = empty(input('field'))?'createtime':trim(input('field'));
        $order = empty(input('sort'))?'ASC':trim(input('sort'));

        $all_balance = 0;
        foreach ($sup as $sup_k=>$sup_v){
            $balance = round($sup_v['opening_payable']-$sup_v['opening_prepayment'],$price_decimal);
            $list = Db::name('kuyou_accounts_copewith')
                ->where($where)
                ->where(['suppliers_id'=>$sup_v['id']])
                ->order([$field=>$order])
                ->select();
            foreach ($list as $list_k=>$list_v){
                $balance    += $list_v['receivable'];
                $balance    -= $list_v['advance'];
            }
            $all_balance    += $balance;
        }

        $info['copewith_unit'] = '元';
        $all_balance = round($all_balance,$price_decimal);
        if($all_balance>10000 || $all_balance<-10000){
            $all_balance = round($all_balance/10000,$price_decimal);
            $info['copewith_unit'] = 'W';
        }else if(($all_balance>1000 && $all_balance<=10000) || ($all_balance<-1000 && $all_balance>=-10000)){
            $all_balance = round($all_balance/1000,$price_decimal);
            $info['copewith_unit'] = 'K';
        }
        $info['copewith'] = $all_balance;


        $sales_list = Db::name('kuyou_goods_sales_order_info')->group('goods_code,goods_attr')->field('goods_code,goods_attr')->select();
        $lists = [];$count = 0;
        foreach ($sales_list as $sales_list_k=>$sales_list_v){
            $row = [];
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$sales_list_v['goods_code']])->find();
            $row['goods_id'] = $goods['id'];
            $row['goods_code'] = $goods['goods_code'];
            $row['goods_name'] = $goods['goods_code'].'_'.$goods['goods_name'];
            $row['goods_image'] = $goods['goods_image'];
            $row['buy_price'] = $goods['purchase'];

            if($goods['min_stock']<=0){
                $goods['min_stock'] = Db::name('kuyou_goods_stock_warning')->where(['goods_code'=>$goods['goods_code']])->sum('min_stock');
            }
            $row['min_stock'] = $goods['min_stock'];

            $where = [];
            $where['goods_code'] = $goods['goods_code'];
            if($sales_list_v['goods_attr']>0){
                $where['attribute_id'] = $sales_list_v['goods_attr'];
            }
            $stock = Db::name('kuyou_goods_stock')->where($where)->field('stock,id,cost_money')->sum('stock');
            $row['stock'] = $stock;

            $row['attr_id'] = '';
            $row['attr_name'] = '';
            if($goods['auxiliary']==1){
                //商品设置属性
                $row['attr_id'] = $sales_list_v['goods_attr'];
                $attribute_id = Db::name('kuyou_goods_attr')->where(['id'=>$sales_list_v['goods_attr']])->value('attribute_id');
                $attribute_ids = Db::name('kuyou_aux_combination')->where(['id'=>$attribute_id])->value('attr_ids');
                if($attribute_ids){
                    $attribute_ids = explode('&',$attribute_ids);
                    $attribute = Db::name('kuyou_auxiliary')->where(['id'=>['in',$attribute_ids]])->column('name');
                    $attribute_name = implode('/',$attribute);
                    $row['attr_name'] = $attribute_name;
                }
            }

            //商品单位
            $unit = Db::name('kuyou_unit')->where(['id'=>$goods['unit_id']])->field('id,name')->find();
            $row['goods_unit'] = $goods['unit_id'];
            $row['unit_name'] = isset($unit['name'])?$unit['name']:'';

            $list = Db::name('kuyou_goods_sales_order_info')->where(['goods_code'=>$sales_list_v['goods_code'],'goods_attr'=>$sales_list_v['goods_attr']])->select();
            $row['number'] = 0;
            foreach ($list as $list_k=>$list_v){
                $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->find();
                $number = $list_v['number'];
                $row['number'] = $number;
                if($goods['more_unit']==1 && $goods['unit_id']!=$list_v['goods_unit']){
                    $advance_rate = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$list_v['goods_unit']])->value('advance_rate');
                    if($advance_rate){
                        $row['number'] = $number*$advance_rate;
                    }
                }
            }

            $list = Db::name('kuyou_goods_purchase_order_info')->where(['goods_code'=>$sales_list_v['goods_code'],'goods_attr'=>$sales_list_v['goods_attr']])->select();
            $row['buy_number'] = 0;
            foreach ($list as $list_k=>$list_v){
                $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->find();
                $number = $list_v['number'];
                $row['buy_number'] = $number;
                if($goods['more_unit']==1 && $goods['unit_id']!=$list_v['goods_unit']){
                    $advance_rate = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$list_v['goods_unit']])->value('advance_rate');
                    if($advance_rate){
                        $row['buy_number'] = $number*$advance_rate;
                    }
                }
            }
            $row['now_buy_number'] = $row['number']-$row['stock']-$row['buy_number']+$row['min_stock'];
            if($row['now_buy_number']<0){
                $row['now_buy_number'] = 0;
            }
            $lists[] = $row;
            $count += $row['now_buy_number'];
        }
        $info['now_buy_number'] = round($count,$number_decimal);

        $list_type = $this->request->post("list_type");
        $list_type = $list_type==2?2:1;

        if($list_type==1){
            //库存预警
            $where = [];
            $where['stock_warning'] = '1';
            $map = [];
            $list = Db::name('kuyou_goods')
                ->where($where)
                ->select();
            $datas = [];
            foreach ($list as $list_k=>$list_v){
                $list[$list_k]['stock'] = $list_v['inventory'];
                if($list_v['branch']==1){
                    $lists = Db::name('kuyou_goods_stock_warning')->alias('sw')
                        ->join('kuyou_stores ks','ks.id=sw.stores_id')->where($map)->where(['sw.goods_code'=>$list_v['goods_code']])
                        ->field('sw.stores_id,sw.min_stock,sw.max_stock,ks.name')->select();
                    foreach ($lists as $lists_k=>$lists_v){
                        $stock = Db::name('kuyou_goods_stock')->where(['goods_code'=>$list_v['goods_code'],'stores_id'=>$lists_v['stores_id']])->value('stock');
                        $datas[] = [
                            'goods_code' => $list_v['goods_code'],
                            'goods_name' => $list_v['goods_name'],
                            'goods_barcode' => $list_v['goods_barcode'],
                            'goods_image' => $list_v['goods_image'],
                            'more_unit' => $list[$list_k]['more_unit'],
                            'stores' => ['name'=>$lists_v['name']],
                            'min_stock' => $lists_v['min_stock'],
                            'max_stock' => $lists_v['max_stock'],
                            'stock' => (float)$stock,
                        ];
                    }
                    unset($list[$list_k]);
                }else{
                    $list[$list_k]['stores'] = ['name'=>'全部仓库'];
                }
            }
            foreach ($datas as $datas_k=>$datas_v){
                $list[] = $datas_v;
            }
            foreach ($list as $list_k=>$list_v){
                if($list_v['stock']>=$list_v['min_stock'] && $list_v['stock']<=$list_v['max_stock']){
                    unset($list[$list_k]);
                }
            }
            $stockworing = sizeof($list);
            $info['stockworing'] = $stockworing;
            //库存预警结束

            //保质期预警
            $info['goods_batch_stock'] = Db::name('kuyou_goods_batch_stock')->alias('gs')
                ->join('kuyou_goods g','g.id=gs.goods_id','left')
                ->join('kuyou_goods_batch b','b.id=gs.batch_id','left')
                ->where(['g.batch'=>'1','gs.stock'=>['>',0]])
                ->group('gs.goods_id,gs.stores_id,gs.batch_id')
                ->count('gs.id');
            //未审核购货订单
            $info['goods_purchase_order'] = Db::name('kuyou_goods_purchase_order')->where(['examine_status'=>'0'])->count();
            //未审核购货单
            $info['goods_purchase'] = Db::name('kuyou_goods_purchase')->where(['examine_status'=>'0'])->count();
            //未审核购货退货单
            $info['goods_exchange'] = Db::name('kuyou_goods_exchange')->where(['examine_status'=>'0'])->count();
            //未审核销货订单
            $info['goods_sales_order'] = Db::name('kuyou_goods_sales_order')->where(['examine_status'=>'0'])->count();
            //未审核销货单
            $info['goods_sales'] = Db::name('kuyou_goods_sales')->where(['examine_status'=>'0'])->count();
            //未审核销货退货单
            $info['sales_exchange'] = Db::name('kuyou_goods_sales_exchange')->where(['examine_status'=>'0'])->count();
            //未审核收款单
            $info['collection'] = Db::name('kuyou_collection')->where(['examine_status'=>'0'])->count();
            //未审核付款单
            $info['payment'] = Db::name('kuyou_payment')->where(['examine_status'=>'0'])->count();
            //未审核其他支出单
            $info['expenditure'] = Db::name('kuyou_expenditure')->where(['examine_status'=>'0'])->count();
            //未审核其他收入单
            $info['income'] = Db::name('kuyou_income')->where(['examine_status'=>'0'])->count();
            //未审核资金转账单
            $info['accounts_transfer'] = Db::name('kuyou_accounts_transfer')->where(['examine_status'=>'0'])->count();
            //未审核调拨单
            $info['allocation'] = Db::name('kuyou_allocation')->where(['examine_status'=>'0'])->count();
            //未审核其他入库单
            $info['warehousing'] = Db::name('kuyou_warehousing')->where(['examine_status'=>'0'])->count();
            //未审核其他出库单
            $info['warehouse'] = Db::name('kuyou_warehouse')->where(['examine_status'=>'0'])->count();
            //未审核组装单
            $info['assemble'] = Db::name('kuyou_assemble')->where(['examine_status'=>'0'])->count();
            //未审核拆卸单
            $info['split'] = Db::name('kuyou_split')->where(['examine_status'=>'0'])->count();
        }
        Cache::set('indexInfo',$info,300);
    }

    function checkParameter($data,$parameter){
        if(is_array($parameter)){
            foreach ($parameter as $parameter_k=>$parameter_v){
                if(strpos($parameter_k,'|') !== false){
                    $k = explode('|',$parameter_k);
                    $name = $k[1];
                    $variable = $k[0];
                }else{
                    $name = $parameter_k;
                    $variable = $parameter_k;
                }
                $parameter_v = empty($parameter_v)?'require':$parameter_v;
                $rule = explode('|',$parameter_v);
                foreach ($rule as $rule_k=>$rule_v){
                    if($rule_v=='requireNone'){
                        if(!isset($data[$variable])){
                            return ['status'=>400,'msg'=>'请输入'.$name.'参数'];
                        }
                    }else if($rule_v=='require'){
                        if(!isset($data[$variable]) || $data[$variable]===''){
                            return ['status'=>400,'msg'=>$name.'参数不正确'];
                        }
                    }else{
                        $rule_row = explode(':',$rule_v);
                        switch ($rule_row[0]){
                            case 'in':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if(!isset($rule_row[1])){
                                        return ['status'=>300,'msg'=>'校验规则错误'];
                                    }
                                    $row_box = explode(',',$rule_row[1]);
                                    if(!in_array($data[$variable],$row_box)){
                                        return ['status'=>400,'msg'=>$name.'参数不正确'];
                                    }
                                }
                                break;
                            case 'between':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if(!isset($rule_row[1])){
                                        return ['status'=>300,'msg'=>'校验规则错误'];
                                    }
                                    $row_box = explode(',',$rule_row[1]);
                                    if($data[$variable]<$row_box[0] || $data[$variable]>$row_box[1]){
                                        return ['status'=>400,'msg'=>$name.'参数不正确'];
                                    }
                                }
                                break;
                            case 'number':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if (!preg_match("/^\d*$/", $data[$variable])){
                                        return ['status'=>400,'msg'=>$name.'只能为数字'];
                                    }
                                }
                                break;
                            case 'letter':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if (!preg_match("/^[a-zA-Z]+$/u", $data[$variable])){
                                        return ['status'=>400,'msg'=>$name.'只能为字母'];
                                    }
                                }
                                break;
                            case 'money':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if (!preg_match("/^[0-9]+(.[0-9]{1,4})?$/", $data[$variable])){
                                        return ['status'=>400,'msg'=>$name.'格式错误'];
                                    }
                                }
                                break;
                            case 'length':
                                if(isset($data[$variable]) && $data[$variable]!==''){
                                    if(!isset($rule_row[1])){
                                        return ['status'=>300,'msg'=>'校验规则错误'];
                                    }
                                    $row_box = explode(',',$rule_row[1]);
                                    if(strlen($data[$variable])<$row_box[0] || strlen($data[$variable])>$row_box[1]){
                                        return ['status'=>400,'msg'=>$name.'字符长度为'.$row_box[0].'-'.$row_box[1].'位'];
                                    }
                                }
                                break;
                            default:
                                return ['status'=>300,'msg'=>'校验规则错误'];
                        }
                    }
                }
            }
        }else{
            $parameter = explode(',',$parameter);
            foreach ($parameter as $k=>$v){
                if(!isset($data[$v]) || $data[$v]===''){
                    return ['status'=>400,'msg'=>'参数不正确'];
                }
            }
        }
        return true;
    }

    function checkCode($code,$type){
        if(empty($code) || empty($type)){
            return false;
        }else{
            $set = \think\Db::name('kuyou_prefix')->where(['type'=>$type])->find();
            if(empty($set)){
                return false;
            }else{
                $prefix = $set['prefix'];
                $code = substr($code, 0, (strlen((string)$prefix)));
                if($prefix!=$code){
                    return false;
                }else{
                    return true;
                }
            }
        }
    }

    function getAdminId(){
        $token = $this->request->server('HTTP_TOKEN', $this->request->request('token', \think\Cookie::get('token')));
        $admin = \think\Cache::get($token);
        return isset($admin['id'])?$admin['id']:0;
    }

    function getSet($name,$field)
    {
        $set = \think\Db::name('kuyou_sets')->where(['name'=>$name])->value($field);
        return $set;
    }

    function getConversion($number,$unit_data)
    {
        $price_decimal = $this->getSet('price_decimal','value');
        $basic_nmber = [];$unit_conversion = [];
        foreach ($unit_data as $unit_data_k=>$unit_data_v){
            if($unit_data_v['advance_rate']>1){
                $basic_nmber[] = (string)(round(($number/$unit_data_v['advance_rate']),$price_decimal)).$unit_data_v['name'];
            }
            $unit_conversion[] = (string)(round(($unit_data[sizeof($unit_data)-1]['advance_rate']/$unit_data_v['advance_rate']),$price_decimal)).$unit_data_v['name'];
        }
        $data['basic_nmber'] = implode('/',$basic_nmber);
        $data['unit_conversion'] = implode('=',$unit_conversion);
        return $data;
    }
    function arraySequence($array, $field, $sort)
    {
        $arrSort = array();
        foreach ($array as $uniqid => $row) {
            foreach ($row as $key => $value) {
                $arrSort[$key][$uniqid] = $value;
            }
        }
        array_multisort($arrSort[$field], constant($sort), $array);
        return $array;
    }

    function getCost_Price($goods,$supplyer_code='',$now_nmber='',$purchase_info=[],$price_taxes='',$valuation_set=1,$set=[]){
        $taxe = \think\Db::name('kuyou_suppliers')->where(['supplyer_code'=>$supplyer_code])->value('vat_rate');
        if($taxe!==0){
            if(empty($taxe)){
                $taxe = \think\Db::name('kuyou_sets')->where(['name'=>'taxes'])->value('value');
            }
        }
        $now_nmbers = (float)$now_nmber;$now_all_money = 0;
        $number = 1;
        $now_nmbers2 = 0;

        while ($now_nmber>0){
            $number++;
            foreach ($purchase_info as $k=>$v){
                if($valuation_set==1){
                    if($now_nmber>0){
                        $now_nmbers2 += $v['basic_nmber'];
                        $now_nmber -= $v['basic_nmber'];
                        $now_all_money += $v['all_money'];
                        $purchase_info[$k]['basic_nmber'] = 0;
                        $purchase_info[$k]['all_money'] = 0;
                        if($now_nmber>=$v['basic_nmber']){
                            $purchase_info[$k]['basic_nmber'] = 0;
                            $purchase_info[$k]['all_money'] = 0;
                        }else{
                            $all_unit = round(($now_all_money/$now_nmbers2)*$now_nmber,4);
                            $purchase_info[$k]['basic_nmber'] -= $now_nmber;
                            $purchase_info[$k]['all_money'] -= $all_unit;
                        }
                    }
                }else{
                    if($now_nmber>=$v['basic_nmber']){
                        $now_nmber -= $v['basic_nmber'];
                        $now_all_money += $v['all_money'];
                        $purchase_info[$k]['basic_nmber'] = 0;
                        $purchase_info[$k]['all_money'] = 0;
                    }else{
                        $unit = round($v['all_money']/$v['basic_nmber'],4);
                        $all_unit = round($unit*$now_nmber,4);
                        $now_all_money += $all_unit;
                        $purchase_info[$k]['basic_nmber'] -= $now_nmber;
                        $purchase_info[$k]['all_money'] -= $all_unit;
                        $now_nmber = 0;
                    }
                }
            }
            if($number>50){
                break;
            }
        }
        if($valuation_set==1){
            $now_nmbers = $now_nmbers2;
        }
        if($now_nmbers!=0){
            $cost = ($now_all_money)/($now_nmbers);
        }else{
            $cost = $goods['purchase'];
            if($set['is_checked']==1){
                if($price_taxes==1){
                    $cost = $cost*100/(100+$taxe);
                }
            }
        }
        return ['cost'=>$cost,'purchase_info'=>$purchase_info];
    }

    function getGoodsCostPrice($goods_code,$number_decimal,$price_decimal,$checkdate,$enable_time,$valuation_set,$stores_set,$price_taxes,$taxes_set,$stores_ids){
        $sort = 'purchase_time';$order='ASC';
        $where = [];
        $where['goods_code'] = $goods_code;
        $list = Db::name('kuyou_goods_sales_info')
            ->where($where)
            ->order($sort, $order)
            ->select();
        if(!empty($list)){
            $map = [];
            if(!empty($checkdate)){
                $map['purchase_time'] = ['>',$checkdate];
            }
            $lists = Db::name('kuyou_goods_sales_info')
                ->where($map)
                ->order($sort, $order)
                ->select();
            $all_money_all = 0;$profit_all = 0;$net_profit_add = 0;
            $map = [];
            if(!empty($checkdate)){
                $map['purchase_time'] = ['>',$checkdate];
            }
            $goods = Db::name('kuyou_goods')->where(['goods_code'=>$goods_code])->find();
            $goods_info = [];
            foreach ($lists as $list_k=>$list_v){
                $cost_all = 0;$pay_money = 0;
                if($list_v['purchase_type']==1){
                    $info = Db::name('kuyou_goods_sales_info')->where(['purchase_code'=>$list_v['purchase_code'],'goods_code'=>$goods_code])->field('pay_money,basic_nmber,goods_code,stores_id,purchase_time')->select();
                    $info_goods = [];
                    foreach ($info as $info_k=>$info_v){
                        if(!isset($goods_info[$info_v['goods_code']])){
                            $where = [];
                            if($stores_set==1){
                                $where['stores_id'] = ['in',$stores_ids];
                            }else{
                                $where['stores_id'] = $info_v['stores_id'];
                            }
                            $where['goods_code'] = $info_v['goods_code'];

                            if(empty($checkdate)){
                                $start_time = strtotime($enable_time);
                                $end_time = strtotime(date('Y-m-d',$info_v['purchase_time']).' 23:59:59');
                                $wheretime['start_time'] = $start_time;
                                $wheretime['end_time'] = $end_time;
                                if(!empty($wheretime)){
                                    $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                                }
                                if($valuation_set==1){
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_time')
                                        ->field('purchase_time,sum(basic_nmber) as basic_nmber,sum(all_money) as all_money')
                                        ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                }else{
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                        ->field('purchase_time,basic_nmber,all_money')
                                        ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                }
                            }else{
                                $checkout_id = Db::name('kuyou_checkout')->order(['checkdate'=>'DESC'])->value('id');
                                $purchase_more = Db::name('kuyou_checkout_info')->where([
                                    'checkout_id'=>$checkout_id,
                                    'goods_code'=>$info_v['goods_code'],
                                ])->find();
                                $purchase_infos = Db::name('kuyou_goods_purchase')->where(['id'=>$purchase_more['purchase_id']])->find();

                                $start_time = $checkdate;
                                $end_time = strtotime(date('Y-m-d',$info_v['purchase_time']).' 23:59:59');
                                $wheretime['start_time'] = $start_time;
                                $wheretime['end_time'] = $end_time;
                                if(!empty($wheretime)){
                                    $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                                }
                                if($valuation_set==1){
                                    $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)->group('purchase_time')
                                        ->field('purchase_time,sum(basic_nmber) as basic_nmber,sum(all_money) as all_money')
                                        ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                    if(!empty($purchase_more)){
                                        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                            if($purchase_info_v['purchase_time']==$purchase_more['purchase_time']){
                                                $purchase_info[$purchase_info_k]['basic_nmber'] = (float)$purchase_more['av_basic_nmber'];
                                                $purchase_info[$purchase_info_k]['all_money'] = (float)$purchase_more['av_all_money'];
                                            }
                                        }
                                    }
                                }else{
                                    if(empty($purchase_more)){
                                        $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                            ->field('purchase_time,basic_nmber,all_money')
                                            ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                    }else{
                                        $where['purchase_code'] = ['>=',$purchase_infos['purchase_code']];
                                        $purchase_info = Db::name('kuyou_goods_purchase_info')->where($where)
                                            ->field('id,purchase_time,basic_nmber,all_money')
                                            ->order(['purchase_time'=>'ASC','purchase_code'=>'ASC'])->select();
                                        foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                            if($purchase_info_v['id']==$purchase_more['purchase_id']){
                                                $purchase_info[$purchase_info_k]['basic_nmber'] = (float)$purchase_more['basic_nmber'];
                                                $purchase_info[$purchase_info_k]['all_money'] = (float)$purchase_more['all_money'];
                                            }
                                        }
                                    }
                                }
                            }

                            $where = [];
                            $where['goods_code'] = $info_v['goods_code'];
                            $where['stores_id'] = ['in',$stores_ids];
                            if(!empty($wheretime)){
                                $where['createtime'] = ['between',[$wheretime['start_time'],time()]];
                            }
                            $period = Db::name('kuyou_goods_period')->where($where)->field('period as basic_nmber,price as all_money,createtime as purchase_time')->find();
                            if(!empty($period)){
                                $period['purchase_time'] = strtotime(date('Y-m-d',$period['purchase_time']));
                                if($valuation_set==1){
                                    $status = true;
                                    foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                        if($purchase_info_v['purchase_time']==$period['purchase_time']){
                                            $status = false;
                                            $purchase_info[$purchase_info_k]['basic_nmber'] += $period['basic_nmber'];
                                            $purchase_info[$purchase_info_k]['all_money'] += $period['all_money'];
                                        }
                                    }
                                    if($status){
                                        $purchase_info[] = $period;
                                        $purchase_info = $this->arraySequence($purchase_info,'purchase_time','SORT_ASC');
                                    }
                                }else{
                                    $purchase_infos = [];
                                    $purchase_infos[] = $period;
                                    foreach ($purchase_info as $k=>$v){
                                        $purchase_infos[] = $v;
                                    }
                                    $purchase_info = $purchase_infos;
                                }
                            }

                            if($goods){
                                $where = [];
                                $where['goods_id'] = $goods['id'];
                                $where['stores_id'] = ['in',$stores_ids];
                                if(!empty($wheretime)){
                                    $where['purchase_time'] = ['between',[$wheretime['start_time'],time()]];
                                }
                                $adjustment_money = 0;
                                $adjustment = Db::name('kuyou_adjustment_info')->where($where)->select();
                                foreach ($adjustment as $adjustment_k=>$adjustment_v){
                                    $advance_rate = 1;
                                    if($adjustment_v['goods_unit']!=$goods['unit_id']){
                                        $unit = Db::name('kuyou_unit_conversion')->where(['main_unit'=>$goods['unit_id'],'vice_unit'=>$adjustment_v['goods_unit']])->value('advance_rate');
                                        if(!empty($unit) && $unit>0){
                                            $advance_rate = $unit;
                                        }
                                    }
                                    $money = $adjustment_v['money']/$advance_rate;
                                    $adjustment[$adjustment_k]['purchase_time'] = strtotime(date('Y-m-d',$adjustment_v['purchase_time']));
                                    $adjustment[$adjustment_k]['all_money'] = $adjustment_v['money'];
                                }
                                foreach ($adjustment as $adjustment_k=>$adjustment_v){
                                    foreach ($purchase_info as $purchase_info_k=>$purchase_info_v){
                                        if($purchase_info_v['purchase_time']==$adjustment_v['purchase_time']){
                                            $purchase_info[$purchase_info_k]['all_money'] += $adjustment_v['all_money'];
                                        }
                                    }
                                }
                            }
                        }else{
                            $purchase_info = $goods_info[$info_v['goods_code']];
                        }

                        $cost = $this->getCost_Price($goods,'',$info_v['basic_nmber'],$purchase_info,$price_taxes,$valuation_set,$taxes_set);

                        if(isset($cost['purchase_info'])){
                            $goods_info[$info_v['goods_code']] = $cost['purchase_info'];
                            $purchase_info = $goods_info[$info_v['goods_code']];
                            $cost = $cost['cost'];
                        }
                        $cost_all += $cost*$info_v['basic_nmber'];
                        $pay_money += $info_v['pay_money'];
                        $info_goods[$info_v['goods_code']] = $cost;
                    }
                }
                $lists[$list_k]['info_goods'] = $info_goods;
                $lists[$list_k]['pay_money'] = $pay_money;
                $lists[$list_k]['sales_cost'] = round($cost_all,$price_decimal);
                $lists[$list_k]['profit'] = round($list_v['all_money']-$cost_all,$price_decimal);
                if($list_v['all_money']>0){
                    $lists[$list_k]['profit_rate'] = round($lists[$list_k]['profit']/$list_v['all_money']*100,2);
                }else{
                    $lists[$list_k]['profit_rate'] = 0;
                }
                $lists[$list_k]['net_profit'] = round($lists[$list_k]['profit']-$list_v['preferential_money']-$list_v['purchase_money'],$price_decimal);
                if($list_v['all_money']>0){
                    $lists[$list_k]['net_profit_rate'] = round($lists[$list_k]['net_profit']/$list_v['all_money']*100,2);
                }else{
                    $lists[$list_k]['net_profit_rate'] = 0;
                }
            }

            foreach ($list as $list_k=>$list_v){
                $status = true;
                foreach ($lists as $lists_k=>$lists_v){
                    if($list_v['id']==$lists_v['id']){
                        $status = false;
                        $list[$list_k]['pay_money'] = $lists[$lists_k]['pay_money'];
                        $list[$list_k]['sales_cost'] = $lists[$lists_k]['sales_cost'];
                        $list[$list_k]['profit'] = $lists[$lists_k]['profit'];
                        $list[$list_k]['profit_rate'] = $lists[$lists_k]['profit_rate'];
                        $list[$list_k]['net_profit'] = $lists[$lists_k]['net_profit'];
                        $list[$list_k]['net_profit_rate'] = $lists[$lists_k]['net_profit_rate'];
                        $list[$list_k]['info_goods'] = $lists_v['info_goods'];
                        $all_money_all += $lists[$lists_k]['all_money'];
                        $profit_all += $lists[$lists_k]['profit'];
                        $net_profit_add += $lists[$lists_k]['net_profit'];
                    }
                }
                if($status){
                    $cost_all = (float)(Db::name('kuyou_goods_sales_profit')
                        ->where(['purchase_code'=>$list_v['purchase_code']])->value('sales_cost'));
                    $list[$list_k]['sales_cost'] = round($cost_all,$price_decimal);
                    $list[$list_k]['profit'] = round($list_v['all_money']-$cost_all,$price_decimal);
                    if($list_v['all_money']>0){
                        $list[$list_k]['profit_rate'] = round($list[$list_k]['profit']/$list_v['all_money']*100,2);
                    }else{
                        $list[$list_k]['profit_rate'] = 0;
                    }
                    $list[$list_k]['net_profit'] = round($list[$list_k]['profit']-$list_v['preferential_money']-$list_v['purchase_money'],$price_decimal);
                    if($list_v['all_money']>0){
                        $list[$list_k]['net_profit_rate'] = round($list[$list_k]['net_profit']/$list_v['all_money']*100,2);
                    }else{
                        $list[$list_k]['net_profit_rate'] = 0;
                    }
                    $list[$list_k]['info_goods'] = [];
                }
            }
            $profit_list = [];$cost_price_list = [];
            foreach ($list as $list_k=>$list_v){
                $profit_list[$list_v['purchase_code']] = $list_v['sales_cost'];
                $cost_price_list[$list_v['purchase_code']] = $list_v['info_goods'];
            }
            unset($list);


            $where = [];
            $where['goods_code'] = $goods_code;
            $lists=[];
            $list = Db::name('kuyou_goods_sales_info')->where($where)->group('goods_code')->field('goods_code')->select();
            foreach ($list as $list_k=>$list_v){
                $goods = Db::name('kuyou_goods')->where(['goods_code'=>$list_v['goods_code']])->field('goods_code,goods_type_id,goods_name')->find();
                if($goods){
                    $c_type = Db::name('kuyou_goods_type')->where(['id'=>$goods['goods_type_id']])->value('supplier_type_name');
                }

                $info = Db::name('kuyou_goods_sales_info')->where(['goods_code'=>$list_v['goods_code']])->select();
                $count = 0;
                $basic_nmber = 0;
                $all_money = 0;
                $tax_money = 0;
                $money_tax_price = 0;
                $cost_all = 0;
                foreach ($info as $info_k=>$info_v){
                    if($info_v['purchase_type']==1){
                        $count += 1;
                        $basic_nmber += $info_v['basic_nmber'];
                        $all_money += $info_v['all_money'];
                        $tax_money += $info_v['tax_money'];
                        $money_tax_price += $info_v['money_tax_price'];
                        $cost_all += isset($profit_list[$info_v['purchase_code']])?$profit_list[$info_v['purchase_code']]:0;
                    }else{
                        $basic_nmber -= $info_v['basic_nmber'];
                        $all_money -= $info_v['all_money'];
                        $tax_money -= $info_v['tax_money'];
                        $money_tax_price -= $info_v['money_tax_price'];
                        $cost_price = isset($cost_price_list[$info_v['purchase_code']])?$cost_price_list[$info_v['purchase_code']]:[];
                        $cost_price = isset($cost_price[$info_v['goods_code']])?$cost_price[$info_v['goods_code']]:'';
                        if($cost_price===''){
                            $cost_price = Db::name('kuyou_goods')->where(['goods_code'=>$info_v['goods_code']])->value('purchase');
                        }
                        $cost_all -= $cost_price*$info_v['basic_nmber'];
                    }
                }
                if($basic_nmber>0){
                    $unit_cost = round($cost_all/$basic_nmber,$price_decimal);
                }else{
                    $unit_cost = 0;
                }
                $profit = $all_money-$cost_all;
                if($profit>0){
                    $profit_rate = round($profit/$all_money*100,2);
                }else{
                    $profit_rate = 0;
                }
                $lists[] = [
                    'c_type_name' => isset($c_type)?$c_type:'',
                    'customer_code' => isset($goods['goods_code'])?$goods['goods_code']:'',
                    'customer_name' => isset($goods['goods_name'])?$goods['goods_name']:'',
                    'count' => $count,
                    'basic_nmber' => round($basic_nmber,$number_decimal),
                    'all_money' => round($all_money,$price_decimal),
                    'tax_money' => round($tax_money,$price_decimal),
                    'money_tax_price' => round($money_tax_price,$price_decimal),
                    'unit_cost' => round($unit_cost,$price_decimal),
                    'cost_all' => round($cost_all,$price_decimal),
                    'profit' => round($profit,$price_decimal),
                    'profit_rate' => round($profit_rate,$price_decimal),
                ];
            }
        }else{
            $lists = [];
        }
        return $lists;
    }

    function getUnit($goods_code='',$store='',$attr='',$supplyer_code=''){
        $set= Db::name('kuyou_sets')->where(['name'=>'taxes'])->field('value,is_checked')->find();
        $taxes= Db::name('kuyou_sets')->where(['name'=>'price_taxes'])->value('is_checked');

        if($goods_code){
            $row = Db::name('kuyou_goods')->where(['goods_code'=>$goods_code])->field('batch,serial,id,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')->find();
            $goods_id = isset($row['id'])?$row['id']:0;
        }else{
            $goods_id = isset($_POST['goods_id'])?$_POST['goods_id']:0;
            $row = Db::name('kuyou_goods')->where(['id'=>$goods_id])->field('batch,serial,auxiliary,unit_id,more_unit,more_unit_id,purchase,goods_code,manager_warehouse_id,batch,shelf_life,warehousing,warehouse')->find();
        }
        if(empty($row)){
            return [];
        }
        if($supplyer_code){
            $suppliers = Db::name('kuyou_suppliers')->where(['supplyer_code'=>$supplyer_code])->value('vat_rate');
        }

        $auxiliary = Db::name('kuyou_auxiliary')->where(['status'=>1])->column('name','id');
        $goods_attr = Db::name('kuyou_goods_attr')->where(['goods_id'=>$goods_id])->select();
        foreach ($goods_attr as $goods_attr_k=>$goods_attr_v){
            $aux_combination = Db::name('kuyou_aux_combination')->where(['id'=>$goods_attr_v['attribute_id']])->value('attr_ids');
            $goods_attr[$goods_attr_k]['attr_ids'] = [];
            $goods_attr[$goods_attr_k]['attr_name'] = '';
            if($aux_combination){
                $goods_attr[$goods_attr_k]['attr_id'] = $aux_combination;
                $aux_combination = explode('&',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_ids'] = $aux_combination;
                foreach ($aux_combination as $aux_combination_k=>$aux_combination_v){
                    $aux_combination[$aux_combination_k] = isset($auxiliary[$aux_combination_v])?$auxiliary[$aux_combination_v]:'';
                }
                $aux_combination = implode('/',$aux_combination);
                $goods_attr[$goods_attr_k]['attr_name'] = $aux_combination;
            }
        }


        $where = [];
        $where['goods_id'] = $goods_id;
        if($store){
            $where['stores_id'] = $store;
        }else{
            $where['stores_id'] = $row['manager_warehouse_id'];
        }
        if($attr){
            $where['attribute_id'] = $attr;
        }
        $stock = Db::name('kuyou_goods_stock')->where($where)->value('stock');
        if($row['more_unit']==1){
            $unit = Db::name('kuyou_unit_conversion')->alias('uc')
                ->join('kuyou_unit u','u.id=uc.vice_unit')
                ->where(['uc.main_unit'=>$row['unit_id']])
                ->order('uc.advance_rate','ASC')
                ->field('uc.vice_unit,u.name,u.id,uc.advance_rate')
                ->select();
            $unit_ids = [$row['unit_id']];
            foreach ($unit as $unit_k=>$unit_v){
                $unit_ids[] = $unit_v['id'];
            }
            $goods_price = Db::name('kuyou_goods_price')->where(['unit'=>['in',$unit_ids],'goods_id'=>$goods_id])->select();
            foreach ($goods_price as $goods_price_k=>$goods_price_v){
                foreach ($unit as $unit_k=>$unit_v){
                    if($goods_price_v['unit']==$row['unit_id']){
                        $goods_price[$goods_price_k]['advance_rate'] = 1;
                    }else if($goods_price_v['unit']==$unit_v['id']){
                        $goods_price[$goods_price_k]['advance_rate'] = $unit_v['advance_rate'];
                    }
                }
            }
        }else{
            $unit_ids = [$row['unit_id']];
        }
        $unit = Db::name('kuyou_unit')->where(['id'=>['in',$unit_ids]])->field('id,name')->select();
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($goods_price)){
                foreach ($goods_price as $goods_price_k=>$goods_price_v){
                    if($unit_v['id']==$goods_price_v['unit']){
                        $unit[$unit_k]['is_default'] = $goods_price_v['is_default'];
                        //$unit[$unit_k]['purchase'] = $goods_price_v['purchase']*$goods_price_v['advance_rate'];
                        $unit[$unit_k]['purchase'] = $goods_price_v['purchase'];
                        if($goods_price_v['is_default']!=1){
                            $unit[$unit_k]['basic_nmber'] = $goods_price_v['advance_rate'];
                        }else{
                            $unit[$unit_k]['basic_nmber'] = 1;
                        }
                    }
                }
            }else{
                if($row['auxiliary']==1 && !empty($attr)){
                    $purchase = Db::name('kuyou_goods_attr')->where(['goods_id'=>$goods_id,'id'=>$attr])->value('purchase');
                }else{
                    $purchase = $row['purchase'];
                }
                if($unit_v['id']==$row['unit_id']){
                    $unit[$unit_k]['is_default'] = 1;
                    $unit[$unit_k]['basic_nmber'] = 1;
                    $unit[$unit_k]['purchase'] = $purchase;
                }
            }
        }
        foreach ($unit as $unit_k=>$unit_v){
            if(isset($suppliers) && $suppliers!==''){
                $tax = $suppliers;
            }else{
                $tax = $set['value'];
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1){
                $unit[$unit_k]['tax'] = 1;
                $unit[$unit_k]['tax_rate'] = $tax;
            }else{
                $unit[$unit_k]['tax'] = 0;
                $unit[$unit_k]['tax_rate'] = 0;
            }
            if(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes==1){
                $unit[$unit_k]['purchase'] = round(($unit_v['purchase']/(100+$tax)*100),4);
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }elseif(isset($set['is_checked']) && isset($set['value']) && $set['is_checked']==1 && $taxes!=1){
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = round(($unit_v['purchase']*(100+$tax)/100),4);
            }else{
                $unit[$unit_k]['purchase'] = $unit_v['purchase'];
                $unit[$unit_k]['tax_included'] = $unit_v['purchase'];
            }
        }
        $data = [];
        foreach ($unit_ids as $unit_ids_k=>$unit_ids_v){
            foreach ($unit as $unit_k=>$unit_v){
                if($unit_ids_v==$unit_v['id']){
                    if($unit_v['is_default']==1){
                        $unit_v['stock'] = is_null($stock)?0:$stock;
                    }else{
                        $unit_v['stock'] = round($stock/$unit_v['basic_nmber'],2);
                    }
                    $unit_v['tax_money'] = round(($unit_v['tax_included']-$unit_v['purchase']),4);;
                    $data[] = $unit_v;
                }
            }
        }
        return json_encode(['unit'=>$data,'attr'=>$goods_attr,'goods'=>$row]);
    }
}
